<?php
namespace app\service\data;

use app\service\models as models;
use app\lib\Code;
use yii;
use Fixtures\Prophecy\EmptyClass;

class Image
{
    
    private $_dsImage;
    private $_dsRecognition;
    private $_dsUser;
    
    private $_calCheckRedisKey = "oct|cal|count";
    
    public function __construct()
    {
        $this->_dsImage= new models\Image();
        $this->_dsRecognition= new models\Recognition();
        $this->_dsUser= new models\User();
        
    }
    
    /**
     * 用户端-添加认可
     */
    public function Ratification($arrInput)
    {
        $data= $this->_dsRecognition->findOne($arrInput['rid']);
        if(empty($data)){
            formatJson(Code::PARAM, "没有图片结果");
        }
        $data->ratification_content= $arrInput['remark'];
        $data->status = 1;
        $data->update_time = date("Y-m-d H:i:s");
        $save = $data->save();
        return $save;
    }
    
    /**
     * 用户端-添加质疑
     */
    public function Oppugn($arrInput)
    {
        $data = $this->_dsRecognition->findOne($arrInput['rid']);
        if(empty($data)){
            formatJson(Code::PARAM, "没有图片结果");
        }
        $data->oppugn_content= $arrInput['content'];
        $data->status = 2;
        $data->update_time = date("Y-m-d H:i:s");
        $save = $data->save();
        return $save;
    }
    
    /**
     * 用户端-添加预留联系方式
     */
    public function Liaison($arrInput)
    {
        $data = $this->_dsRecognition->findOne($arrInput['rid']);
        if(empty($data)){
            formatJson(Code::PARAM, "没有图片结果");
        }
        $data->phone = $arrInput['phone'];
        $data->email = $arrInput['email'];
        $data->update_time = date("Y-m-d H:i:s");
        $save = $data->save();
        return $save;
    }
    
    /*
     * 上传图片
     */
    public function Upload($arrInput) {
        $uid = yii::$app->session['uid']->value;
        if(!$uid) {
            formatJson(Code::PARAM, "请重新登录");
        }
        $count = $this->_dsImage->find()->where(['uid'=>$uid,'status'=>0, 'is_del'=>0])->count();
        if($count >= 30) {
            formatJson(Code::PARAM, "当前未识别的图片已超过30张，请识别后再上传");
        }
        
        $uploadInfo = $this->uploadImage($arrInput);
        
        $this->_dsImage->image_url = $uploadInfo['image_url'];
        $this->_dsImage->real_path = $uploadInfo['real_path'];
        $this->_dsImage->uid = $uid;
        $ret = $this->_dsImage->save();
        if(!$ret) {
            formatJson(Code::PARAM, "文件上传失败");
        }
        
        return [
            'image_url'=>$uploadInfo['image_url'],
        ];
    }
    
    //上传图片文件
    private function uploadImage($arrInput) {
        if(empty($_FILES) || empty($_FILES['file'])) {
            formatJson(Code::PARAM, "文件不存在，请选择上传文件");
        }
        $filepath = $_FILES['file']['tmp_name'];
        $filename = $_FILES['file']['name'];
        $ext = end(explode('.', $filename));
        $realpath = '/var/www/html/otc-fe/OCT/file/src/'.time().'.'.$ext;
    
        $ret = move_uploaded_file($filepath, $realpath);
        if(!$ret) {
            formatJson(Code::PARAM, "文件上传失败");
        }
        
        //检测图片宽高是否合法
        $imageInfo = getimagesize($realpath);
        if($imageInfo[0] != $imageInfo[1]) {
            unlink($realpath);
            formatJson(Code::PARAM, "请上传正方形图片用于算法识别");
        }
        
        return [
            'real_path' => $realpath,
            'image_url' => 'http://www.oct.ai/file/src/'.time().'.'.$ext,
        ];
    }
    
    /*
     * 用户端-获取图片列表
     */
     public function GetLastImageList($uid) {
//          return $uid;
         $ret = $this->_dsImage
            ->find()
            ->where(['uid'=>$uid, 'is_del'=>0])
            ->orderBy('id desc')
            ->all();
         
         if(!$ret) {
             return [];
         }
         
         $datalist = [];
         foreach ($ret as $value) {
             $datalist[] = $value->toArray([
                 'id',
                 'image_url',
                 'status',
             ]);
         }
         return $datalist;
    }
    
    /**
     * 后端-获取用户的图片列表
     */
    public function GetUserImageList($uid, $page=1, $pagesize=10) {
        $count = $this->_dsImage
            ->find()
            ->where(['uid'=>$uid, 'is_del'=>0])
            ->count();
        
        $ret = $this->_dsImage
            ->find()
            ->where(['uid'=>$uid, 'is_del'=>0])
            ->offset(($page-1)*$pagesize)
            ->limit($pagesize)
            ->orderBy('id desc')
            ->all();
         
        if(!$ret) {
            return [
                'page'=>$page,
                'page_size'=>$pagesize,
                'total'=>0,
                'data_list'=>[],
            ];
        }
         
        $datalist = [];
        foreach ($ret as $value) {
            $datalist[] = $value->toArray([
                'id',
                'image_url',
                'status',
            ]);
        }
        return [
                'page'=>$page,
                'page_size'=>$pagesize,
                'total'=>intval($count),
                'data_list'=>$datalist,
            ];
    }
    
    /**
     * 删除图片
     */
    public function DelImage($uid,$imageId) {
        $ret = $this->_dsImage->find()->where(['id'=>$imageId, 'uid'=>$uid])->one();
        if(!$ret) {
            formatJson(Code::PARAM, '图片不存在');
        }
        $ret->is_del = 1;
        $retn = $ret->save();
        
        return $retn ? true : false;
    }
    
    /**
     * 进行图像识别
     */
    public function ImageRecognition($uid,$imageId) {
        //获取图片信息
        $imageret = $this->_dsImage->find()->where(['id'=>$imageId])->one();
        if(!$imageret || $imageret->status != 0) {
            return $imageret->status;
        }
        
        $imageInfo = $imageret->toArray([
            'id',
            'image_url',
            'real_path',
            'status',
        ]);
        
        $this->_dsRecognition->uid = $uid;
        $this->_dsRecognition->image_id = $imageId;
        
        $pices = explode('/', $imageInfo['image_url']);
        $filename = $pices[count($pices)-1];
        
        $this->_dsRecognition->real_path = "/var/www/html/otc-fe/OCT/file/ret/{$filename}"; //识别后的图片存放路径
        $this->_dsRecognition->content = "http://www.oct.ai/file/ret/{$filename}"; //识别后的图片url
        
        //获取识别结果
        $this->_dsRecognition->status = 0;
        $newret = $this->_dsRecognition->save();
        
        //设置图片为识别中
        $imageret = $this->_dsImage->find()->where(['id'=>$imageId])->one();
        $imageret->status = 1;
        $imageret->save();
        
        return 1;
    }
    
    /**
     * 获取最新的识别结果
     * @param unknown $imageId
     */
    public function GetLastRecognition($imageId) {
        $ret = $this->_dsRecognition
            ->find()
            ->where(['image_id'=>$imageId])
            ->orderBy('id desc')
            ->one();
        if(!$ret) {
            formatJson(Code::PARAM, '图像未识别');
        }
        
        $data = $ret->toArray([
            'id',
            'uid',
            'content',
            'recognition_ret',
            'create_time',
            'ratification_content',
            'oppugn_content',
            'phone',
            'email',
            'status',
            'update_time',
        ]);
        
        $imageInfo = $this->_dsImage->find()->where(['id'=>$imageId])->one()->toArray(['image_url']);
        $data['image_url'] = $imageInfo['image_url'];
        
        return $data;
    }
    
    /**
     * 用户-图片列表
     */
    public function ImageList($arrInput) {
        $count = $this->_dsImage
        ->find()
        ->count();
        $ret = $this->_dsImage
        ->find()
        ->offset(($arrInput['page'] - 1) * $arrInput['page_size'])
        ->limit($arrInput['page_size'])
        ->all();
        
        $data_list = [];
        
        foreach ($ret as $value) {
            $data_list[] = $value->toArray([
                'id',
                'uid',
                'image_url',
                'is_del',
                'status',
                'create_time',
            ]);
        }
        
        foreach ($data_list as $key=>$value) {
            $user_info = $this->_dsUser->findOne($value['uid']);
            $user_info = $user_info->toArray([
                'id',
                'phone',
                'hospital_name',
                'email',
                'create_time',
            ]);
            $data_list[$key]['phone'] =  $user_info['phone'];
            $data_list[$key]['hospital_name'] =  $user_info['hospital_name'];
            $data_list[$key]['email'] =  $user_info['email'];
            
            $rec_info = $this->_dsRecognition
                ->find()
                ->where(['image_id'=>$value['id']])
                ->orderBy('id desc')
                ->one();
//                 $ret = $this->_dsRecognition
//                 ->find()
//                 ->where(['image_id'=>$imageId])
//                 ->orderBy('id desc')
//                 ->one();
                
            
            if(!$rec_info) {
                $data_list[$key]['content'] = $rec_info->content;
            } else {
                $data_list[$key]['content'] = '';
            }
        }
        
        return [
            "total_size"=>intval($count),
            "page"=>$arrInput['page'],
            "page_size"=>$arrInput['page_size'],
            "data_list"=>$data_list,
        ];
    }
    
    /**
     * 图片识别列表
     */
    public function RecognitionList($arrInput) {
        //图片信息
        $image_info = $this->_dsImage->findOne($arrInput['image_id']);
        $image_info = $image_info->toArray([
            'id',
            'uid',
            'image_url',
            'is_del',
            'status',
            'create_time',
        ]);
        $user_info = $this->_dsUser->findOne($image_info['uid']);
        $user_info = $user_info->toArray([
            'id',
            'phone',
            'hospital_name',
            'email',
            'create_time',
        ]);
        $codition = ['image_id'=>$arrInput['image_id']];      
        $count = $this->_dsRecognition
        ->find()
        ->where($codition)
        ->count();
        $ret = $this->_dsRecognition
        ->find()
        ->where($codition)
        ->offset(($arrInput['page'] - 1) * $arrInput['page_size'])
        ->limit($arrInput['page_size'])
        ->all();
        
        $data_list = [];
        
        foreach ($ret as $value) {
            $data_list[] = $value->toArray([
                'id',
                'uid',
                'content',
                'create_time',
                'recognition_ret',
                'ratification_content',
                'oppugn_content',
                'phone',
                'email',
                'status',
                'update_time',
            ]);
        }
        
        return [
            "total_size"=>intval($count),
            "page"=>$arrInput['page'],
            "page_size"=>$arrInput['page_size'],
            "image_info"=>$image_info,
            "user_info"=>$user_info,
            "data_list"=>$data_list,
        ];
    }
    
    /**
     * 下载图片
     */
    //下载模板
    public function DownloadImage($imageId) {
        $ret = $this->_dsImage->find()->where(['id'=>$imageId])->one();
        $file = $ret->real_path;
        if(file_exists($file)) {
            header("Content-type:application/octet-stream");
            $filename = basename($file);
            header("Content-Disposition:attachment;filename = ".$filename);
            header("Accept-ranges:bytes");
            header("Accept-length:".filesize($file));
            readfile($file);
        }else{
            return '文件不存在';
        }
    
        return true;
    }
    
}
